import React, { useEffect, useRef, useState } from "react";
import { Table, Row, Col, Input, Form, Button, Switch, Space, Divider, Image, message, Modal, Select, Cascader } from 'antd'
import Prefix from '../../components/prefix'
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import * as apis from '../../lib/api'
import * as tool from '../../lib/tool'
import http from '../../lib/http'
import _ from 'lodash'
import Add from './add'
import { handleValue } from '../../components/upload'
import { useNavigate } from "react-router-dom";


const Index = (props) => {
    const [search, setSearch] = useState({page: 1,page_size: 20})
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState()
    const [seleckeys, setSeleckeys] = useState([])
    const [category, setCategory] = useState([])
    const [orgCategory, setOrgCategory] = useState([])
    const [orgPubCategory, setOrgPubCategory] = useState([])
    
    const [pubCategory, setPubCategory] = useState([])
    const [curPubCategoryId, setCurPubCategoryId] = useState([])
    const [curItem, setCurItem] = useState()
    const [pubModalOpen, setPubModalOpen] = useState()

    const addRef = useRef()
    const n = useNavigate()

    const loadData = async (s) => {
        try {
            if(s.category_id && s.category_id[0]){
                s.category_id = s.category_id[0]
            }
            if(s.category_id && s.category_id[1]){
                s.second_category_id = s.category_id[1]
            }
            if(s.category_id && s.category_id[2]){
                s.three_category_id = s.category_id[2]
            }
            setData(await http.post(apis.MODEL_LIST,s))
            setSeleckeys([])
        } catch (error) {
            
        }
    }

    const onSearch = async (values) => {
        let cpSearch = {...search}
        cpSearch.name = values?.name
        cpSearch.category_id = values?.category_id
        cpSearch.page = 1
        cpSearch.status = values?.status
        cpSearch.is_pub = values?.is_pub
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const pageSearch = async (page,page_size) => {
        let cpSearch = {...search}
        cpSearch.page_size = page_size
        cpSearch.page = page
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const showChange = async (checked,v) => {
        
    }

    const del = async (ids) => {
        setLoading(true)
        try {
            await http.post(apis.MODEL_DELETE,{ids})
            message.success("操作成功")
            await loadData(search)
        } catch (error) {
            
        }
        setLoading(false)
    }

    const updatePub = async (param) => {
        
    }

    const add = () => {
        addRef.current.setIsModalOpen(true)
        addRef.current.resetFields()
        addRef.current.setFieldsValue({})
    }

    const edit = (v) => {
        addRef.current.setIsModalOpen(true)
        addRef.current.resetFields()
        const updateData = {
            id: v.id,
            category_id: [v.category_id, v.second_category_id, v.three_category_id], 
            name: v.name, 
            cover: handleValue(v.cover),
            path: handleValue(v.path),
            design_file_path: handleValue(v.design_file_path),
            tags: v.tags ? v.tags.split(","):[],
            items: v.items
        }
        let new_category_id = []
        for(let i=0;i<updateData.category_id.length;i++){
            if(updateData.category_id[i] !== 0){
                new_category_id.push(updateData.category_id[i])
            }
        }
        updateData.category_id = new_category_id
        addRef.current.setFieldsValue(updateData)
    }

    const onRefresh = async (isInit) => {
        if(!isInit){
            setLoading(true)
            await loadData(search)
            setLoading(false)
            return
        }
        let cpSearch = {...search}
        cpSearch.page = 1
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    useEffect(()=>{
        setLoading(true)
        loadData(search).then(r => {
            setLoading(false)
        })

        http.post(apis.MODEL_CATEGORY_LIST,{is_pub: 2, status: 1}).then(r => {
            setCategory(tool.handleLevelData(r))
            setOrgCategory(r)
        })
        http.post(apis.MODEL_CATEGORY_LIST,{is_pub: 1, status: 1}).then(r => {
            setPubCategory(tool.handleLevelData(r))
            setOrgPubCategory(r)
        })

        // http.post(apis.MODEL_PUB_CATEGORY_LIST,{page: 1,page_size: 100,status: 1}).then(r => {
        //     setPubCategory(r?.list)
        // })
        // eslint-disable-next-line
    },[])

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: '名字',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: '标签',
            dataIndex: 'tags',
            key: 'tags'
        },
        {
            title: '所属分类',
            dataIndex: 'category_id',
            key: 'category_id',
            render: (v,r) => {
                const cs = [r.category_id,r.second_category_id,r.three_category_id]
                const txt = []
                for(let i=0;i<cs.length;i++){
                    let f = orgCategory.find(s => s.id === cs[i])
                    if(f){
                        txt.push(f.name)
                    }
                }
                return <span>{txt.join()}</span>
            }
        },
        {
            title: '封面',
            dataIndex: 'cover',
            key: 'cover',
            render: (v) => (
                <Image src={process.env.REACT_APP_OSS_URL+v+"?x-oss-process=image/resize,w_300"} width={60} height={60} fallback="" />
            )
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at'
        },
        {
            title: '操作',
            dataIndex: 'a',
            key: 'a',
            render: (v,r) => (
                <>
                    <Button loading={loading} type="link" onClick={()=> edit(r)} style={{padding: 0}}>编辑</Button>
                    {/* <Divider type="vertical" />
                    <Button loading={loading} type="link" onClick={()=>{
                        n(`/model/m_item_config?id=${r.id}`)
                    }} style={{padding: 0}}>部件配置</Button> */}
                    <Divider type="vertical" />
                    <Button loading={loading} type="link" onClick={async ()=>{
                        setLoading(true)
                        try {
                            let ret = await http.post(apis.DESIGN_CREATE,{
                                name: "默认白模",
                                model_id: r.id,
                                is_new: true,
                                cache_save: true
                            })
                            let token = await http.get(apis.PC_TOKEN)
                            let domA = document.createElement("a")
                            domA.href = `${process.env.REACT_APP_PC_URL}/login/auto?id=${ret.id}&token=${token}`
                            domA.target = "_blank"
                            domA.click()
                        } catch (error) {
                            
                        }
                        setLoading(false)
                    }} style={{padding: 0}}>发布</Button>
                    {/* <Divider type="vertical" />
                    <Button loading={loading} style={{padding: 0}} type="link" danger onClick={()=> {
                         Modal.confirm({
                            title: "提示",
                            content: <p>确定删除吗?</p>,
                            onOk: async () => {
                                await del([r.id])
                            }
                        })
                    }}>删除</Button> */}
                </>
            )
        }
    ]

    return (
        <div>
            <Modal 
                title="提示"
                open={pubModalOpen}
                onCancel={()=>{
                    setPubModalOpen(false)
                }}
                onOk= {async () => {
                    if(curPubCategoryId.length === 0){
                        message.error("请选择分类")
                        return
                    }
                    await updatePub({
                        id: curItem.id,
                        is_pub: 1,
                        pub_category_id: curPubCategoryId[0] ? curPubCategoryId[0]:0,
                        second_pub_category_id: curPubCategoryId[1] ? curPubCategoryId[1]:0,
                        three_pub_category_id: curPubCategoryId[2] ? curPubCategoryId[2]:0
                    })
                    setPubModalOpen(false)
                }}
            >
                <div>
                    <p>公开后，所有人可见，请选择公开后所属分类：</p>
                    <Cascader style={{width: "100%"}} value={curPubCategoryId} onChange={(v)=> setCurPubCategoryId(v)} allowClear options={pubCategory} placeholder="请选择" />
                </div>
            </Modal>
            <Add category={category} funcs={addRef} onRefresh={onRefresh} />
            <Form onFinish={onSearch}>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item name="name">
                            <Prefix label="名称">
                                <Input allowClear placeholder="请输入名称" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="category_id">
                            <Prefix label="所属分类">
                                <Cascader allowClear options={category} placeholder="请选择" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item>
                            <Space>
                                <Button loading={loading} type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
                                <Button onClick={add} loading={loading} ghost type="primary" icon={<PlusOutlined />}>新增</Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            {/* <Space>
                <span>已选 {seleckeys?.length} 条</span>
                <Button danger disabled={seleckeys?.length === 0} onClick={() => {
                    Modal.confirm({
                        title: "提示",
                        content: <p>确定删除 <span style={{color: 'red'}}>{seleckeys?.length}条</span> 数据吗?</p>,
                        onOk: async () => {
                            await del(seleckeys)
                        }
                    })
                }}>批量删除</Button>
            </Space>
            <div style={{height: 12}}></div> */}
            <Table 
                rowKey={'id'}
                dataSource={data?.list || []} 
                loading={loading} 
                columns={columns}
                pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    onChange: pageSearch,
                    total: data?.total,
                    current: data?.page,
                    pageSize: data?.page_size
                }}
                scroll={{
                    y: 'calc(100vh - 410px)'
                }}
                rowSelection={{
                    onChange: (keys) => {
                        setSeleckeys(keys)
                    },
                    selectedRowKeys: seleckeys
                }}
            />
        </div>
    )
}

export default Index